package com.example.shiro.controller;

import com.example.shiro.entity.SysUser;
import com.example.shiro.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;


@RestController
@RequestMapping("/sys")
public class SysUserController {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/loginmsg")
    public String loginmsg(){
        return "{code:200,msg:\"请先登录\"}";
    }
    @RequestMapping("/login")
    public String login(@RequestParam(required=true)String username, @RequestParam(required=true)String password){
        // 添加用户认证信息
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        // 进行验证，这里可以捕获异常，然后返回对应信息
        try {
            SecurityUtils.getSubject().login(usernamePasswordToken);
        } catch (UnknownAccountException e){
            return "账号不存在";
        }catch (IncorrectCredentialsException e){
            return "密码不正确";
        }catch (LockedAccountException e){
            return "该用户已锁定";
        }
        return "登录成！";
    }

    @RequestMapping("/add")
    public void addUser(SysUser sysUser) {
        //加密 盐 随机数
        String salt = UUID.randomUUID().toString().replace("-","");
        //Sha类型加密 密码 盐 10000次迭代
        String password = new Sha256Hash(sysUser.getPassword(), salt, 10000).toBase64();
        //数据库中存放加密的密码
        sysUser.setPassword(password);
        //数据库中存放加密盐
        sysUser.setSalt(salt);
        sysUserService.add(sysUser);
    }

    public static void main(String[] args) {
        //加密 盐 随机数
        String salt = UUID.randomUUID().toString().replace("-","");
        //Sha类型加密 密码 盐 10000次迭代
        String password = new Sha256Hash("lzf", salt, 1000).toBase64();
        //数据库中存放加密的密码 +d6YP/7wkAt7ylQKA9JW11RhZ//Qi8iM7TGwIsjh7vw=

        System.out.println(password);
        System.out.println(salt);
    }
}
